
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.os.Looper
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.base.App
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * Created by cj on 2021/2/22.
 * Email:codesexy@163.com
 * Function:
 * desc:为整个应用提供位置信息
 */
class LocationPool private constructor(
    private val mDispatchEngine: ExecutorService = Executors.newSingleThreadExecutor(),
    private val mHandler: Handler = Handler(Looper.getMainLooper())
) {

    /**
     * 当前定位结果
     */
    private var currentLocation: AMapLocation? = null

    private var observers: MutableList<LocationChangeObserver> = mutableListOf()

    companion object {
        private var instance: LocationPool? = null
            get() {
                if (field == null) {
                    field = LocationPool()
                }
                return field
            }

        fun get(): LocationPool {
            return instance!!
        }
    }

    /**
     * 获取当前定位信息
     */
    fun getCurrentLocation(): AMapLocation? = currentLocation

    /**
     * 开始定位
     */
    fun start() {
        mDispatchEngine.submit {
            startLocation()
        }
    }

    /**
     * 开始分发消息
     */
    private fun startDispatch(location: AMapLocation) {
        mDispatchEngine.submit {
            try {
                observers.forEach {
                    mHandler.post {
                        try {
                            it.onChange(location)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
    }
    fun onRefreshWaterListDispatch() {
        mDispatchEngine.submit {
            try {
                observers.forEach {
                    mHandler.post {
                        try {
                            it.onRefreshWaterList()
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
    }

    /**
     * 开始定位
     */
    private fun startLocation() {
        var mLocationClient = AMapLocationClient(App.get())
        mLocationClient.setLocationListener {
            currentLocation = it
            startDispatch(it)
        }
        var mLocationOption = AMapLocationClientOption()
        mLocationOption.isSensorEnable = true
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy;
        mLocationOption.interval = 1000 * 15
        mLocationOption.isNeedAddress = true
        mLocationOption.httpTimeOut = 20000
        mLocationClient.enableBackgroundLocation(2001,buildNotification())
        mLocationClient.setLocationOption(mLocationOption)
        mLocationClient.startLocation()
    }


    fun registerLocationObserver(observer: LocationChangeObserver) {
        observers.add(observer)
    }


    fun unRegisterLocationObserver(observer: LocationChangeObserver) {
        observers.remove(observer)
    }


    interface LocationChangeObserver {
        fun onChange(location: AMapLocation)
        fun onRefreshWaterList(){}
    }

    private var notificationManager:NotificationManager? = null
    private var isCreateChannel = false
    private val NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";

    private fun buildNotification(): Notification? {
        var builder: Notification.Builder? = null
        var notification: Notification? = null
        if (Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (null == notificationManager) {
                notificationManager =
                    App.get()?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
            }
            val channelId: String = App.get()!!.packageName
            if (!isCreateChannel) {
                val notificationChannel = NotificationChannel(
                    channelId,
                    NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT
                )
                notificationChannel.enableLights(true) //是否在桌面icon右上角展示小圆点
                notificationChannel.lightColor = Color.BLUE //小圆点颜色
                notificationChannel.setShowBadge(true) //是否在久按桌面图标时显示此渠道的通知
                notificationManager?.createNotificationChannel(notificationChannel)
                isCreateChannel = true
            }
            builder = Notification.Builder(App.get(), channelId)
        } else {
            builder = Notification.Builder(App.get())
        }
        builder.setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("智能车载平板")
            .setContentText("正在后台运行")
            .setWhen(System.currentTimeMillis())
        notification = if (Build.VERSION.SDK_INT >= 16) {
            builder.build()
        } else {
            return builder.notification
        }
        return notification
    }

}